package JavaEE_notes.common_API.Thread.pojo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author TaiZai
 * @data 2024/9/24 20:03
 */
public class Account {
    private String cardId;
    private double money;
    private final Lock lk = new ReentrantLock();

    public Account(String cardId, double money) {
        this.cardId = cardId;
        this.money = money;
    }

    // 不加锁的情况，出现共享资源冲突的问题
    /* public void drawMoney(double money) {
        // 确定取钱的人
        String name = Thread.currentThread().getName();
        // 判断余额
        if (this.money >= money) {
            System.out.println(name + "取出" + money + "元");
            this.money -= money;
            System.out.println(name + "取钱后余额为" + this.money + "元");
        } else {
            System.out.println(name + "取钱, 余额不足");
        }
    } */

    // 采用同步代码块的方式加锁
    /* public void drawMoney(double money) {
        // 确定取钱的人
        String name = Thread.currentThread().getName();
        // 判断余额
        synchronized (this) { // this代表共享资源
            if (this.money >= money) {
                System.out.println(name + "取出" + money + "元");
                this.money -= money;
                System.out.println(name + "取钱后余额为" + this.money + "元");
            } else {
                System.out.println(name + "取钱, 余额不足");
            }
        }
    } */

    // 采用同步方法的方式加锁
    /* public synchronized void drawMoney(double money) {
        // 确定取钱的人
        String name = Thread.currentThread().getName();
        // 判断余额
        if (this.money >= money) {
            System.out.println(name + "取出" + money + "元");
            this.money -= money;
            System.out.println(name + "取钱后余额为" + this.money + "元");
        } else {
            System.out.println(name + "取钱, 余额不足");
        }
    } */

    // 采用Lock 接口的方式加锁 需要在成员变量中创建一个 Lock 接口的实现类对象
    public synchronized void drawMoney(double money) {
        // 确定取钱的人
        String name = Thread.currentThread().getName();
        try {
            lk.lock(); // 获取锁
            // 判断余额
            if (this.money >= money) {
                System.out.println(name + "取出" + money + "元");
                this.money -= money;
                System.out.println(name + "取钱后余额为" + this.money + "元");
            } else {
                System.out.println(name + "取钱, 余额不足");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lk.unlock(); // 释放锁
        }
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }
}
